import asyncio
from lib.net.index import wlan
from lib.websocket import action
from lib.sensors.inmp441.recorder import Inmp441

__service__ = "voice_ws_audio"
__description__ = "upload i2s audio to websocket server"


def init():
    if not wlan.is_connected():
        print("wifi not connected")


mic = Inmp441(2, 1, 0)
headers = [("Content-Type", "audio/pcm")]
index = 1


async def run():
    global index
    await action.connect(headers)

    while True:
        try:
            # 确保连接状态
            if not await action.ws_client.open():
                await action.connect(headers)

            pcm_data = mic.record_bytes(1024)
            index = index + 1
            print(index, ",", len(pcm_data))
            await action.send_data(bytes(pcm_data))
            # 保持原来的10ms间隔，确保音频连续性
            await asyncio.sleep_ms(80)
        except Exception as e:
            print(f"发送数据出错: {e}")
            # 短暂等待后继续，不中断音频流
            await asyncio.sleep_ms(100)


if __name__ == "__main__":
    print("开始语音WebSocket音频演示...")
    print("连接WiFi...")

    # 初始化WiFi连接
    if not wlan.is_connected():
        print("正在连接WiFi...")
        wlan.connect()

    if wlan.is_connected():
        print("开始录音并发送到WebSocket服务器...")

        # 运行主循环
        try:
            asyncio.run(run())
        except KeyboardInterrupt:
            print("演示结束")
        except Exception as e:
            print(f"运行出错: {e}")
    else:
        print("WiFi连接失败，请检查配置")
